/**
 * 类名：点单服务类目管理业务类
 * 备注：负责点单服务类目管理业务逻辑。
 * 作者：rankin
 * 日期：2016/03/10
 */
var CafeCategory = require('../models/CafeCategory');
var User = require('../models/User');

var ObjectID = require('mongodb').ObjectID;
var debug = require('debug')('controller:cafecategory');
var async = require('async');
var _ = require('underscore');


//数据库错误响应
function handleError(err, res) {
    debug('Happend error response fail to client. [%o]', err);
    res.send({success: false, msg: err});
};

module.exports = {

    /**
     * 跳转到列表页
     * @param req
     * @param res
     */
    list: function (req, res) {

        if (req.session.permissionMap[4012]) {//没有4010权限，则需要按用户查询
            User.find().exec().then(function (users) {
                res.render('cafe/category_list', {users: users});
            });
        } else {
            res.render('cafe/category_list');
        }
    },
    /**
     * 获得categories列表的json数据格式
     * @param req
     * @param res
     */
    categories: function (req, res) {

        debug('Got a request to [categories],request body is [%o].', req.body);

        //获取请求参数
        var parent_id = req.query.parent;

        //组织查询参数
        var params = {
            parent_id: parent_id
        };

        if (req.session.permissionMap[4012]) {
            params.system_user_id = req.query.suid;
        } else {
            params.system_user_id = req.session.user._id;
        }

        CafeCategory.find(params, function (err, categories) {
            if (err) {
                handleError(err, res);
                return;
            }
            //响应数据
            res.send({success: true, data: categories});
        });
    },
    /**
     * 增加商品目录
     * @param req
     * @param res
     */
    create: function (req, res) {

        debug('Got a request to [create],request body is [%o].', req.body);

        //获取请求参数
        var name = req.body.name;
        var parent_id = req.body.parent;
        var suid = req.body.suid;

        //数据格式验证
        if (!name) {    //名称必须不为空
            res.send({success: false, msg: '目录名称必须不为空.'});
            debug('The parameter "name" can not be empty，response fail to client.');
            return;
        }

        //获得父目录
        if (parent_id) {
            debug('Find the CafeCategory from db by parent_id=[%s].', parent_id);
            //查询目录是否存在
            CafeCategory.findOne({_id: ObjectID(parent_id)}, function (err, category) {
                if (err) {
                    handleError(err, res);
                } else {
                    //判断目录是否存在
                    if (!category) {
                        //父目录不存在，创建目录失败.
                        res.send({success: false, msg: '父目录不存在，创建目录失败.'});
                        debug('The CafeCategory does not exists  by "parent_id"，response fail to client.');
                    } else {
                        hanldeCreate(null, category);
                    }
                }
            });
        } else {
            debug('The parameter "parent_id" is empty,create a first level CafeCategory.');
            hanldeCreate(null, null);
        }

        function hanldeCreate(err, category) {
            //创建目录
            var newModel = {
                name: name,
                level: category ? category.level + 1 : 1,
                parent_id: category ? category.id : '',
                system_user_id: req.session.permissionMap[4012] ? suid : req.session.user._id,
                create_date: new Date()
            };
            debug('Create a new CafeCategory instance to DB. [%o]', newModel);
            //保存新目录
            CafeCategory.create(newModel, function (err, newCategory) {
                if (err) {
                    handleError(err);
                } else {
                    //保存成功
                    res.send({success: true, data: newCategory});
                    debug('The CafeCategory create is successful,response success to client.');
                }
            });
        }

    },
    /**
     * 删除商品目录
     * @param req
     * @param res
     */
    remove: function (req, res) {

        debug('Got a request to [remove],request params is [%o].', req.params);

        //获取请求参数
        var id = req.params.id;

        //数据格式验证
        if (!id) {    //名称必须不为空
            res.send({success: false, msg: '目录ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }

        //删除目录
        debug('Delete the CafeCategory and Children from db by id=[%s].', id);
        CafeCategory.find().or([{_id: ObjectID(id)}, {parent_id: id}]).remove(function (err) {
            if (err) {
                handleError(err, res);
                return;
            } else {
                //删除成功
                res.send({success: true});
                debug('The CafeCategory was deleted，response success to client.');
            }
        });
    },
    /**
     * 编辑商品目录
     * @param req
     * @param res
     */
    edit: function (req, res) {

        debug('Got a request to [edit],request params is [%o],request body is [%o].', req.params, req.body);

        //获取请求参数
        var id = req.params.id;
        var name = req.body.name;

        //数据格式验证
        if (!id) {    //ID必须不为空
            res.send({success: false, msg: '目录ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }
        if (!name) {    //名称必须不为空
            res.send({success: false, msg: '目录名称必须不为空.'});
            debug('The parameter "name" can not be empty，response fail to client.');
            return;
        }

        //查询目录
        debug('Edit the CafeCategory to db by id=[%s] , fields=[{name:%s}].', id, name);
        CafeCategory.findOne({_id: ObjectID(id)}, function (err, category) {
            if (err) {
                handleError(err, res);
                return;
            } else {
                //更新目录名
                category.name = name;
                category.save(function (err) {
                    res.send({success: true});
                    debug('The CafeCategory was edited，response success to client.');
                });
            }
        });

    }
};